package com.cherrypt.api.core.util;

import com.cherrypt.api.model.dataobject.Config;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Field;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class CherryUtils {
    private static final Logger logger = LoggerFactory.getLogger(CherryUtils.class);
    private static String serverUrl;

    public static Config config;

    public static String getUploadFilePath() {
        return Paths.get("").toAbsolutePath().toString();
    }

    /**
     * 创建文件夹
     *
     * @param dir 文件夹路径
     * @return
     */
    public static File createDir(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 获取server的ip地址
     *
     * @param request request
     * @return http://localhost:7290/api
     */
    public static String getServerUrl(HttpServletRequest request) {
        if (serverUrl == null) {
            int port = request.getLocalPort();
            serverUrl = request.getRequestURL().toString().replace(request.getServletPath(), "");
            serverUrl = serverUrl.replaceFirst(":\\d+", ":" + port);
            logger.info("This server url is: {}", serverUrl);
        }
        return serverUrl;
    }

    /**
     * 随机一个数再MD5
     *
     * @return hash
     */
    public static String randomCode() {
        Random random = new Random();
        int code = random.nextInt(99999999);
        return DigestUtils.md5Hex(String.valueOf(code).getBytes());
    }

    public static String getNewToken(int uid) {
        // 生成token
        return JwtUtils.createJWTToken(CherryUtils.config.getTokenSecret(), uid, CherryUtils.config.getTokenExp());
    }
}
